package main

/*
	优雅启停服务
*/
import (
	"context"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	r := gin.Default()
	r.GET("/grace", func(context *gin.Context) {

		time.Sleep(10*time.Second)
		context.String(200,"hello,grace\n")
	})

	var server = &http.Server{
		Addr:              ":8088",
		Handler:           r,
	}
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen %s\n", err)
		}
	}()

	//ctrl+c(SIGNIT) && kill -15(当程序释放相应资源后再停止)
	quit:=make (chan os.Signal)
	signal.Notify(quit,syscall.SIGINT,syscall.SIGTERM)
	<- quit
	log.Println("shutdown -server\n")

	ctx,cancel:=context.WithTimeout(context.Background(),10*time.Second)
	defer cancel()
	if err:=server.Shutdown(ctx);err!=nil{
		log.Fatal("server shutdown\n")

	}
	log.Println("server exiting")

	r.Run()
}
